import React, {useState} from "react";
import {StyleSheet, Text, View} from "react-native";
import SpinnerIndicator from "./SpinnerIndicator.tsx";

const styles = StyleSheet.create({
    backdrop: {
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'rgba(0,0,0,0.4)',
        zIndex: 999
    },
    overlay: {
        padding: 20,
        borderRadius: 10,
        maxWidth: '50%',
        alignItems: 'center',
        justifyContent: 'center',
        rowGap: 10,
    },
    description: {
        fontSize: 14,
        color: '#f5f5f5'
    }
});

const LoaingBase = React.forwardRef((props: any, ref: any) => {
    const [visible, setVisible] = useState<boolean>(false);
    const [description, setDescription] = useState<string | undefined>("");

    React.useImperativeHandle(ref, () => ({
        show: (description?: string) => {
            setDescription(description);
            setVisible(true);
        },
        hide: () => {
            setDescription("");
            setVisible(false);
        },
        update: (description?: string) => {
            setDescription(description);
        }
    }));

    if (!visible) {
        return <></>
    }

    return (
        <View style={[StyleSheet.absoluteFill, styles.backdrop]}>
            <View style={styles.overlay}>
                <SpinnerIndicator color={'#f5f5f5'}/>
                {description && <Text style={styles.description}>{description}</Text>}
            </View>
        </View>
    )
});

let loadingRef: any = null;
const Loading = () => {
    const ref = React.useRef<any>(null);

    React.useEffect(() => {
        if (ref.current) {
            loadingRef = ref.current;
        }
    }, []);
    return <LoaingBase ref={ref}/>
}

Loading.show = (description?: string) => {
    loadingRef?.show(description);
}

Loading.hide = () => {
    loadingRef?.hide();
}

Loading.update = (description?: string) => {
    loadingRef?.update(description);
}

export default Loading;
